package com.lanou.projecta_163news.adapter.newsAdapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanou.projecta_163news.R;

import java.util.List;

/**
 * Created by dllo on 16/3/7.
 */
public class NewsRecyclerAdapter extends RecyclerView.Adapter<NewsRecyclerAdapter.NewsRvViewHolder> {
    private List<News> newsData;
    private NewsItemListener newsItemListener;

    public void setNewsItemListener(NewsItemListener newsItemListener) {
        this.newsItemListener = newsItemListener;
    }

    public void addNewsData(List<News> newsData) {
        this.newsData = newsData;
        notifyDataSetChanged();
    }

    @Override
    public NewsRvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_news_item, null);
        return new NewsRvViewHolder(view);
    }

    @Override
    public void onBindViewHolder(NewsRvViewHolder holder, int position) {
        if (newsData != null && newsData.size() > 0) {
            News news = newsData.get(position);
            holder.rvIv.setImageResource(news.getImageId());
            holder.titleTv.setText(news.getNewsTitles());
            holder.contextTv.setText(news.getNewsContent());
            holder.position = position;

        }

    }

    @Override
    public int getItemCount() {
        return newsData != null && newsData.size() > 0 ? newsData.size() : 0;
    }

    public class NewsRvViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView titleTv, contextTv;
        private ImageView rvIv;
        private int position;
        private LinearLayout rvitemline;

        public NewsRvViewHolder(View itemView) {
            super(itemView);
            titleTv = (TextView) itemView.findViewById(R.id.news_rvitem_tv_title);
            contextTv = (TextView) itemView.findViewById(R.id.news_rvitem_tv_context);
            rvIv = (ImageView) itemView.findViewById(R.id.news_rvitem_iv);
            rvitemline = (LinearLayout) itemView.findViewById(R.id.news_rvitem_line);
            //添加监听 监听(1)
            rvitemline.setOnClickListener(this);

        }

        @Override//监听(2)
        public void onClick(View v) {
            News n = newsData.get(position);
            if (newsItemListener != null) {
                newsItemListener.newsItemListener(n);
            }
        }
    }
}
